﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Web.Http;
using Yz.Model.Constants;

namespace Yz.ApiService.Controllers
{
    public class ApiBaseController : ApiController
    {
        [HttpGet]
        public HttpResponseMessage Get()
        {
            string content = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath("~/About/Index.html"), Encoding.UTF8);
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(content, Encoding.UTF8, "text/html")
            };
            return result;
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="lgnName"></param>
        /// <param name="lgnPwd"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Login")]
        [AllowAnonymous]
        public string Login(string lgnName, string lgnPwd, int expireMinutes)
        {
            var byteJwt = Convert.FromBase64String(Config.JwtSecretKey);
            var tokenHandler = new JwtSecurityTokenHandler();

            var now = DateTime.UtcNow;
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                        {
                        new Claim(ClaimTypes.Name, lgnName)
                    }),
                Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(byteJwt), SecurityAlgorithms.HmacSha256Signature)
            };

            var stoken = tokenHandler.CreateToken(tokenDescriptor);
            var token = tokenHandler.WriteToken(stoken);

            return token;
        }
    }
}
